<?php

namespace app\company\controller;

use app\common\enum\Status;
use app\common\model\SalesmanDealer;
use app\common\model\Store;
use app\common\model\Dealer;
use app\common\model\Salesman as SalesmanModel;
use app\common\controller\CompanyController;
use app\common\model\SalesmanStore;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\company\model\DealerStore;
use app\Request;
use think\App;
use think\facade\Db;
use think\response\Json;

/**
 * @ControllerAnnotation(title="业务员管理")
 */
class Salesman extends CompanyController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SalesmanModel();
        $this->sort  = ['sort' => 'desc', 'id' => 'desc'];
        $this->each  = true;
    }

    public function list(): Json
    {
        // 组合查询参数
        list($limit, $where) = $this->buildSearchParams();
        // 获取列表数据
        $sql = $this->model;
        foreach ($where as $k => $v) {
            if (str_contains($v[0], 'dealer_id')) {

                $salesmanIds = SalesmanDealer::where('dealer_id', $v[2])->column('salesman_id');
                $sql      = $sql->where('id', 'in', $salesmanIds);
                unset($where[$k]);
            }
        }
        if ($this->relationSearch) {
            // 使用 array_filter 确保 $this->joinTable 是一个非空数组
            $joinTables = array_filter(explode(',', $this->joinTable));
            if (count($joinTables) > 1) {
                $sql = $sql->withJoin($joinTables, 'LEFT');
            } else {
                // 如果只有一个表，直接调用 withJoin
                $sql = $sql->withJoin($this->joinTable, 'LEFT');
            }
        }
        if ($this->defaultWhere) $sql = $sql->where($this->defaultWhere);
        $list = $sql->where($where)->order($this->sort)->paginate($limit);
        if ($this->each) $list = $this->each($list);
        return $this->success($list);
    }

    public function each($list)
    {
        return $list->each(function ($vo)
        {
            $dealer     = $vo->dealer()->find();
            $vo->dealer = $dealer ?
                    (new Dealer())->where('id', $dealer->dealer_id)->field('id,name')->find() : "";
        });
    }

    /**
     * @NodeAnnotation(title="门店列表")
     */
    public function store(): Json
    {
        $get = $this->request->get();
        if (!$get['salesman_id'] || !$get['dealer_id']) return $this->error('参数错误');
        // 过滤绑定过的门店
        $bindStoreIds = SalesmanStore::where('salesman_id', $get['salesman_id'])
                                     ->where('company_id', $this->companyId)
                                     ->column('store_id');
        $storeIds     = DealerStore::where('dealer_id', $get['dealer_id'])
                                   ->where('company_id', $this->companyId)
                                   ->whereNotIn('store_id', $bindStoreIds)
                                   ->column('store_id');
        $sql          = new Store();
        $list         = $sql->where('company_id', $this->companyId)
                            ->where('status', 1)->whereIn('id', $storeIds)->field('id,name,lon,lat')
                            ->select();
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="添加")
     */
    public function add(Request $request): Json
    {
        try {
            $this->checkPost();
            $post = $request->post();
            $rule = [
                    'username|账号名称' => 'require|unique:salesman,username,company_id^delete_time',
                    'rename|姓名' => 'require',
                    'phone|手机号' => 'require|max:11|unique:salesman,phone,company_id^delete_time',
            ];
            $this->validate($post, $rule);
            if (empty($post['password'])) $post['password'] = '123456';
            $post['password']   = password($post['password']);
            $post['company_id'] = $this->companyId;
            $this->model->transaction(function () use ($post)
            {
                $save = $this->model->save($post);
                // 绑定经销商ID
                if ($save && !empty($post['dealer_id'])) {
                    (new SalesmanDealer())->save(['salesman_id' => $this->model->id, 'dealer_id' => $post['dealer_id'], 'company_id' => $this->companyId]);
                }
            });
        } catch (\Exception $e) {
            return $this->error('保存失败' . $e->getMessage() . $e->getFile() . $e->getLine());
        }
        return $this->success('保存成功');
    }

    public function unbound(): Json
    {
        $get = $this->request->get();
        if (!$get['id']) return $this->error('参数错误');
        // 经销商ID
        $dealerId = SalesmanDealer::where('salesman_id', $get['id'])->value('dealer_id');
        // 经销商门店ID
        $dealerStoreIds = DealerStore::where('dealer_id', $dealerId)->where('company_id', $this->companyId)->column('store_id');
        // 业务员已经绑定的门店ID
        $bindStoreIds = SalesmanStore::where('salesman_id', $get['id'])->where('company_id', $this->companyId)->column('store_id');
        // 过滤绑定门店
        $storeIds = array_diff($dealerStoreIds, $bindStoreIds);
        if(!$storeIds) return $this->error('没有可绑定的门店');
        $sql = "select `id`,`name`,`address`,`contact` from vk_store where `company_id` = {$this->companyId} 
                                                       and `status` = 1 and `id` in (".implode(',', $storeIds).")";
        $list = Db::query($sql);
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="绑定门店")
     */
    public function bind(Request $request, $id = 0): Json
    {
        $this->checkPost();
        $storeIds = $request->post('store_id', '');
        if (!$storeIds) return $this->error('请选择门店');
        $sql      = new SalesmanStore();
        $storeIds = explode(',', $storeIds);
        // 自动过滤已经绑定的门店
        $bindStoreIds = $sql->where('salesman_id', $id)->whereIn('store_id', $storeIds)->column('store_id');
        $storeIds     = array_diff($storeIds, $bindStoreIds);
        if (!$storeIds) return $this->success('保存成功');
        try {
            $this->model->transaction(function () use ($id, $storeIds, &$save)
            {
                $data = array_map(function ($storeId) use ($id)
                {
                    return ['company_id' => $this->companyId, 'salesman_id' => $id, 'store_id' => $storeId];
                }, $storeIds);
                $save = (new SalesmanStore())->saveAll($data);
            });
        } catch (\Exception $e) {
            $this->error('保存失败');
        }
        if ($save) return $this->success('保存成功');
        return $this->error('保存失败');
    }

    /**
     * @NodeAnnotation (title="解绑门店")
     */
    public function unbind(Request $request, $id = 0): Json
    {
        $this->checkPost();
        $storeIds = $request->post('store_id', '');
        if (!$storeIds) return $this->error('请选择门店');
        $sql      = new SalesmanStore();
        $storeIds = explode(',', $storeIds);
        try {
            $this->model->transaction(function () use ($id, $storeIds, $sql)
            {
                $sql->where('salesman_id', $id)->whereIn('store_id', $storeIds)->delete();
            });
        } catch (\Exception $e) {
            return $this->error('解绑失败');
        }
        return $this->success('解绑成功');
    }

    /**
     * @NodeAnnotation (title="编辑")
     */
    public function edit(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $rule = [
                'id' => 'require|integer'
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) return $this->error('数据不存在！');
        if (!empty($post['password'])) $post['password'] = password($post['password']);
        $this->sceneValidate($post, 'edit');
        try {
            $this->model->transaction(function () use ($post, $row)
            {
                $row->save($post);
                $salesmanDealer = new SalesmanDealer();
                if (isset($post['dealer_id'])) {
                    $salesmanDealer->where('salesman_id', $row->id)->delete();
                    $salesmanDealer->save(['salesman_id' => $row->id, 'dealer_id' => $post['dealer_id'], 'company_id' => $this->companyId]);
                }
            });
        } catch (\Exception $e) {
            return $this->error('编辑失败');
        }
        return $this->success('编辑成功');
    }
}